package com.ezjie.login.core.http;

import java.io.File;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ezjie.baselib.core.http.HttpRequestCallBack;
import com.ezjie.baselib.util.LogUtils;
import com.ezjie.login.InterfaceInfo.ServiceInterface;
import com.ezjie.login.core.base.HttpHeaderBean;
import com.ezjie.login.db.UserInfoDB;
import com.ezjie.login.model.UserDetail;
import com.ezjie.login.util.SystemUtils;
import com.igexin.sdk.PushManager;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Context;

public class HttpAPI {
	static Context mContext;
	private static final int TIME_OUT = 1000 * 0;
	private final HttpUtils http = new HttpUtils();
	private static String mApiBaseUrl;
	private static final boolean USESSL = false;
	private static HttpAPI httpUtil;
	public static String getScheme() {
		return USESSL ? "https://" : "http://";
	}
	public HttpAPI(Context context) {
		// TODO Auto-generated constructor stub
		super();
	}
	public static HttpAPI getInstance(Context context,String BaseUrl) {
		mContext = context;
		mApiBaseUrl = getScheme() + BaseUrl;
		if (httpUtil == null) {
			httpUtil = new HttpAPI(context);
		}
		return httpUtil;
	}
	
	private RequestParams assemblyGetRequestParams(Map<String, String> params) {
		RequestParams requestParams = new RequestParams();

		requestParams.addHeader("parameters", requestParameters());
		if (params != null) {
			if (!params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
					LogUtils.d("Param: " + entry.getKey() + ":" + entry.getValue());
					requestParams.addQueryStringParameter(entry.getKey(),
							entry.getValue() == null ? "" : entry.getValue());
				}
			}
		}
		return requestParams;
	}
	private String fullUrl(String url) {
		return mApiBaseUrl + url;

	}
	/**
	 * 发送POST请求
	 * @param path
	 * @param params
	 * @param httpRequestCallback
	 */
	public void doPostRequest(String path,Map<String, String> params,final HttpRequestCallBack httpRequestCallback){
        http.configCurrentHttpCacheExpiry(TIME_OUT);//设置超时时间
        LogUtils.d(fullUrl(path));
        
        http.send(HttpMethod.POST, fullUrl(path), assemblyPostRequestParams(params,null), new RequestCallBack<String>() {//接口回调  
        	@Override
        	public void onStart() {
        		httpRequestCallback.onStartCallBack();
        	}
        	
        	@Override
        	public void onLoading(long total, long current, boolean isUploading) {
        		httpRequestCallback.onLoadingCallBack(total, current, isUploading); 
        	}
        	
            @Override  
            public void onFailure(HttpException error, String msg) {  
                httpRequestCallback.onFailureCallBack(error, msg);  
            }  
  
            @Override  
            public void onSuccess(ResponseInfo<String> info) {  
                httpRequestCallback.onSuccessCallBack(info.result);
            } 
        });      	    	
    }
	
	public String requestParameters() {
		UserInfoDB userInfoDB = new UserInfoDB(mContext);
		UserDetail userDetail = userInfoDB.queryLoginUser();
		HttpHeaderBean headerBean = new HttpHeaderBean();
		headerBean.setApp_name("ezjie.android.ieltsezj");
		headerBean.setApp_version(SystemUtils.getVersion(mContext));
		headerBean.setCid(PushManager.getInstance().getClientid(mContext));
		headerBean.setDevice(SystemUtils.getBrand(mContext));
		headerBean.setDevice_id(SystemUtils.getIMEI(mContext));
		headerBean.setDevice_token("");
		headerBean.setLogin_key(userDetail.login_key);
		headerBean.setNationality(mContext.getResources().getConfiguration().locale.getCountry());
		headerBean.setSystem("Android");
		headerBean.setSystem_version(SystemUtils.getSystemVersion());
		headerBean.setUid(userDetail.uid);
		headerBean.setVersion_code(SystemUtils.getVersionCode(mContext));

		String jsonStr = JSONObject.toJSON(headerBean).toString();
		LogUtils.d("parameters:" + jsonStr);
		return jsonStr;
	}

	private RequestParams assemblyPostRequestParams(Map<String, String> params, Map<String, File> files) {
		RequestParams requestParams = new RequestParams();
		requestParams.addHeader("parameters", requestParameters());
		if (params != null) {
			if (!params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
					LogUtils.d("Param: " + entry.getKey() + ":" + entry.getValue());
					requestParams.addBodyParameter(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
				}
			}
		}

		if (files != null) {
			if (!files.isEmpty()) {
				for (Map.Entry<String, File> entry : files.entrySet()) {// 构建表单字段内容

					LogUtils.d("Param: " + entry.getKey() + ":" + entry.getValue());

					requestParams.addBodyParameter(entry.getKey(), entry.getValue());
				}
			}
		}

		return requestParams;
	}
	

}
